import axios from "axios"
import qs from "qs"

axios.defaults.baseURL = "http://127.0.0.1:5000/"
axios.defaults.timeout = 5000
axios.interceptors.request.use(
  config => {
    const token: string = JSON.parse(localStorage.getItem("t_k")!)
    if (token) {
      config.headers.Authorization = token
    }
    return config
  },
  err => {
    console.log(err)
  },
)
axios.interceptors.response.use(
  // 响应拦截器
  res => {
    return res.data
  },
  err => {
    console.log(err)
  },
)

export function get(url: string, params: unknown): Promise<unknown> {
  return new Promise((resolve: any, reject: any): Promise<any> => {
    // eslint-disable-next-line no-promise-executor-return
    return axios
      .get(url, {
        params,
      })
      .then(res => {
        resolve(res)
      })
      .catch(err => {
        reject(err)
      })
  })
}
export function post(url: string, data: unknown): Promise<unknown> {
  return new Promise((resolve, reject) => {
    // eslint-disable-next-line no-promise-executor-return
    return axios
      .post(url, qs.stringify(data))
      .then(res => {
        resolve(res)
      })
      .catch(err => {
        reject(err)
      })
  })
}
